{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "разбор ДЗ 3.ipynb",
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3 (ipykernel)",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.8.12"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gjqfVuVBkbeH"
      },
      "source": [
        "## Практическое задание\n",
        "\n",
        "Все задания рекомендуется делать вручную, затем проверяя полученные результаты с использованием numpy.\n",
        "\n",
        "__1.__ Установить, какие произведения матриц $AB$ и $BA$ определены, и найти размерности полученных матриц:\n",
        "\n",
        "   а) $A$ — матрица $4\\times 2$, $B$ — матрица $4\\times 2$;\n",
        "    \n",
        "   б) $A$ — матрица $2\\times 5$, $B$ — матрица $5\\times 3$;\n",
        "    \n",
        "   в) $A$ — матрица $8\\times 3$, $B$ — матрица $3\\times 8$;\n",
        "    \n",
        "   г) $A$ — квадратная матрица $4\\times 4$, $B$ — квадратная матрица $4\\times 4$.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JOHrEvH6kbeW"
      },
      "source": [
        "а) Перемножить нельзя\n",
        "б) AB 2X3\n",
        "в) AB 8X8, BA 3X3\n",
        "г) АВ BA 4X4"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "njKd8N4Gkbeh"
      },
      "source": [
        "__2.__ Найти сумму и произведение матриц $A=\\begin{pmatrix}\n",
        "1 & -2\\\\ \n",
        "3 & 0\n",
        "\\end{pmatrix}$ и $B=\\begin{pmatrix}\n",
        "4 & -1\\\\ \n",
        "0 & 5\n",
        "\\end{pmatrix}.$\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "khBsA0Wmkbek"
      },
      "source": [
        "### $$A+B\n",
        "=\n",
        "\\begin{pmatrix}\n",
        "1 & -2\\\\ \n",
        "3 & 0\n",
        "\\end{pmatrix} \n",
        "+\n",
        "\\begin{pmatrix}\n",
        "4 & -1\\\\ \n",
        "0 & 5\n",
        "\\end{pmatrix}=$$\n",
        "\n",
        "### $$=\n",
        "\\begin{pmatrix}\n",
        "1 + 4 & -2 -1\\\\ \n",
        "3 + 0 & 0 + 5\n",
        "\\end{pmatrix}\n",
        "= \n",
        "\\begin{pmatrix}\n",
        "5 & -3\\\\ \n",
        "3 &  5\n",
        "\\end{pmatrix}$$"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kXyChfBKkbeq"
      },
      "source": [
        "### $$AB\n",
        "=\n",
        "\\begin{pmatrix}\n",
        "1 & -2\\\\ \n",
        "3 & 0\n",
        "\\end{pmatrix}\n",
        "\\cdot \n",
        "\\begin{pmatrix}\n",
        "4 & -1\\\\ \n",
        "0 & 5\n",
        "\\end{pmatrix}\n",
        "=$$ \n",
        "### $$=\\begin{pmatrix}\n",
        "1\\cdot 4 + -2\\cdot 0 & 1\\cdot (-1) -2\\cdot 5 \\\\ \n",
        "3\\cdot 4 + 0\\cdot 0 & 3\\cdot (-1) + 0\\cdot 5\n",
        "\\end{pmatrix} \n",
        "=\\begin{pmatrix}\n",
        "4 & -11\\\\ \n",
        "12 & -3\n",
        "\\end{pmatrix}$$"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CU84HTfCkbes"
      },
      "source": [
        "### $$BA\n",
        "= \n",
        "\\begin{pmatrix}\n",
        "4 & -1\\\\ \n",
        "0 & 5\n",
        "\\end{pmatrix}\n",
        "\\cdot  \n",
        "\\begin{pmatrix}\n",
        "1 & -2\\\\ \n",
        "3 & 0\n",
        "\\end{pmatrix}\n",
        "=$$\n",
        "### $$=\n",
        "\\begin{pmatrix}\n",
        "4\\cdot 1 + -1\\cdot 3 & 4\\cdot (-2) + -1\\cdot 0 \\\\ \n",
        "0\\cdot 1 + 5\\cdot 3 & 0\\cdot (-2) + 5\\cdot 0\n",
        "\\end{pmatrix}\n",
        "= \n",
        "\\begin{pmatrix}\n",
        "1 & -8\\\\ \n",
        "15 & 0\n",
        "\\end{pmatrix}$$"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2TEmz14skbez",
        "outputId": "e83aabed-4c8e-4fc2-c680-aad0cb5ff7eb"
      },
      "source": [
        "import numpy as np\n",
        "A = np.array([[1, -2], [3, 0]])\n",
        "B = np.array([[4, -1], [0, 5]])\n",
        "print(f'Матрица A\\n{A}')\n",
        "print(f'Матрица B\\n{B}')\n",
        "print(f'Матрица С = A + B\\n{A + B}')\n",
        "print(f'Матрица AB\\n{np.dot(A, B)}')\n",
        "print(f'Матрица BА\\n{np.dot(B, A)}')"
      ],
      "execution_count": null,
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Матрица A\n",
            "[[ 1 -2]\n",
            " [ 3  0]]\n",
            "Матрица B\n",
            "[[ 4 -1]\n",
            " [ 0  5]]\n",
            "Матрица С = A + B\n",
            "[[ 5 -3]\n",
            " [ 3  5]]\n",
            "Матрица AB\n",
            "[[  4 -11]\n",
            " [ 12  -3]]\n",
            "Матрица BА\n",
            "[[ 1 -8]\n",
            " [15  0]]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aFtMNEL4kbfG"
      },
      "source": [
        "__3.__ Из закономерностей сложения и умножения матриц на число можно сделать вывод, что матрицы одного размера образуют линейное пространство. Вычислить линейную комбинацию $3A-2B+4C$ для матриц $A=\\begin{pmatrix}\n",
        "1 & 7\\\\ \n",
        "3 & -6\n",
        "\\end{pmatrix}$, $B=\\begin{pmatrix}\n",
        "0 & 5\\\\ \n",
        "2 & -1\n",
        "\\end{pmatrix}$, $C=\\begin{pmatrix}\n",
        "2 & -4\\\\ \n",
        "1 & 1\n",
        "\\end{pmatrix}.$"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ruiEFduDkbfJ"
      },
      "source": [
        "### $$3A-2B+4C=$$\n",
        "\n",
        "### $$\\begin{pmatrix}\n",
        "3 & 21\\\\ \n",
        "9 & -18\\\\\n",
        "\\end{pmatrix}\n",
        "+\n",
        "\\begin{pmatrix}\n",
        "0 & -10\\\\ \n",
        "-4 & 2\\\\\n",
        "\\end{pmatrix}\n",
        "+\n",
        "\\begin{pmatrix}\n",
        "8 & -16\\\\ \n",
        "4 & 4\\\\\n",
        "\\end{pmatrix}\n",
        "=$$\n",
        "### $$\n",
        "=\n",
        "\\begin{pmatrix}\n",
        "3+0+8 & 21-10-16\\\\ \n",
        "9-4+4 & -18+2+4\\\\\n",
        "\\end{pmatrix}\n",
        "=\n",
        "\\begin{pmatrix}\n",
        "11 & -5\\\\ \n",
        "9 & -12\n",
        "\\end{pmatrix}$$"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "YAibYm6xkbfT",
        "outputId": "2f2a1e4b-1ffb-4334-dd45-e4167a352cc3"
      },
      "source": [
        "A = np.array([[1, 7], [3, -6]])\n",
        "B = np.array([[0, 5], [2, -1]])\n",
        "C = np.array([[2, -4], [1, 1]])\n",
        "print(f'Матрица 3𝐴−2𝐵+4𝐶\\n{3 * A - 2 * B + 4 * C}')"
      ],
      "execution_count": null,
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Матрица 3𝐴−2𝐵+4𝐶\n",
            "[[ 11  -5]\n",
            " [  9 -12]]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2jzZery9kbfU"
      },
      "source": [
        "__4.__ Дана матрица $A=\\begin{pmatrix}\n",
        "4 & 1\\\\ \n",
        "5 & -2\\\\ \n",
        "2 & 3\n",
        "\\end{pmatrix}$.\n",
        "Вычислить $AA^{T}$ и $A^{T}A$."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "zfoxOQKlkbfV",
        "outputId": "66a54f73-2375-4453-fa9e-7bfd3b1a2df4"
      },
      "source": [
        "A = np.array([[4, 1], [5, -2], [2, 3]])\n",
        "print(f'Матрица:\\n{A}')\n",
        "print(f'Транспонированная матрица:\\n{A.T}')\n",
        "print(f'Матрица 𝐴*𝐴𝑇\\n{np.dot(A,A.T)}')\n",
        "print(f'Матрица 𝐴𝑇*𝐴\\n{np.dot(A.T,A)}')"
      ],
      "execution_count": null,
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Матрица:\n",
            "[[ 4  1]\n",
            " [ 5 -2]\n",
            " [ 2  3]]\n",
            "Транспонированная матрица:\n",
            "[[ 4  5  2]\n",
            " [ 1 -2  3]]\n",
            "Матрица 𝐴*𝐴𝑇\n",
            "[[17 18 11]\n",
            " [18 29  4]\n",
            " [11  4 13]]\n",
            "Матрица 𝐴𝑇*𝐴\n",
            "[[45  0]\n",
            " [ 0 14]]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nZxGGa0okbfW"
      },
      "source": [
        "__5*.__ Написать на Python функцию для перемножения двух произвольных матриц, не используя NumPy."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "g9xNQbwLkbfX"
      },
      "source": [
        "def skalar_prod(v1, v2):\n",
        "    return sum([i * j for i, j in zip(v1, v2)])\n",
        "       \n",
        "def matrix_product(A, B, display_result=True):\n",
        "    result = []\n",
        "    try:\n",
        "        for row_a in A:\n",
        "            internal_row = []\n",
        "            for k in range(len(B[0])):\n",
        "                column = [B[i][k] for i in range(len(B))]\n",
        "                internal_row.append(skalar_prod(row_a, column))\n",
        "            result.append(internal_row)\n",
        "        if display_result:\n",
        "            for row in result:\n",
        "                print(row)\n",
        "        return result\n",
        "    except Exception as e:\n",
        "        print('wrong dimensions!')\n",
        "        print(e)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BhHcTfXVkbfZ",
        "outputId": "7acf0a23-1b94-476d-a542-2ee35d239486"
      },
      "source": [
        "# Проверка\n",
        "a = [[1,2,3],\n",
        "     [5,3,7]]\n",
        "b = [[1,1],\n",
        "     [2,2],\n",
        "     [3,3]]\n",
        "с = matrix_product(a,b)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[14, 14]\n",
            "[32, 32]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gxPD4dVfkbfa",
        "outputId": "48d8f7a8-0105-43df-f172-6f934b8265aa"
      },
      "source": [
        "# Сравнение с NUMPY\n",
        "import numpy as np\n",
        "a_np = np.array(a)\n",
        "b_np = np.array(b)\n",
        "a_np.dot(b_np)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[14, 14],\n",
              "       [32, 32]])"
            ]
          },
          "execution_count": 3,
          "metadata": {
            "tags": []
          },
          "output_type": "execute_result"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ELVcm75Ekbfc"
      },
      "source": [
        ""
      ],
      "execution_count": null,
      "outputs": []
    }
  ]
}